#!/bin/bash
# 启动 XrayGLM 模型推理服务
# 独立部署的模型推理后端
# 带自动重启功能，确保服务持续运行

# 移除 set -e，允许服务在错误时继续运行

# 配置
CONDA_ENV_NAME="visualglm"
CONDA_BASE_PATH="/data/Matrix/common/miniconda3"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 从环境变量读取配置，或使用默认值
GPU_ID="${GPU_ID:-0}"
PORT="${PORT:-8010}"
API_TOKEN="${API_TOKEN:-}"

echo "=========================================="
echo "启动 XrayGLM 模型推理服务"
echo "=========================================="
echo "GPU ID: $GPU_ID"
echo "端口: $PORT"
echo "API Token: ${API_TOKEN:+已设置}"
echo "=========================================="

# 激活 Conda 环境
echo "激活 Conda 环境: $CONDA_ENV_NAME"
if [ -f "$CONDA_BASE_PATH/bin/activate" ]; then
  source "$CONDA_BASE_PATH/bin/activate" "$CONDA_ENV_NAME" || {
    echo "❌ 激活 Conda 环境失败"; exit 1; }
else
  echo "❌ 未找到 Conda 激活脚本: $CONDA_BASE_PATH/bin/activate"; exit 1
fi

# 设置环境变量
export GPU_ID
export PORT
if [ -n "$API_TOKEN" ]; then
  export API_TOKEN
fi

# 切换到脚本目录
cd "$SCRIPT_DIR"

# PID 文件路径
PID_FILE="$SCRIPT_DIR/model_inference_service.pid"
LOG_FILE="$SCRIPT_DIR/model_inference.log"

# 检查是否已有服务在运行
if [ -f "$PID_FILE" ]; then
    OLD_PID=$(cat "$PID_FILE")
    if ps -p "$OLD_PID" > /dev/null 2>&1; then
        echo "⚠️  服务已在运行 (PID: $OLD_PID)"
        echo "如需重启，请先停止: kill $OLD_PID"
        exit 0
    else
        echo "清理旧的 PID 文件..."
        rm -f "$PID_FILE"
    fi
fi

# 启动服务函数
start_service() {
    echo "启动模型推理服务..."
    echo "日志输出到: $LOG_FILE"
    nohup python xrayglm_inference_service.py > "$LOG_FILE" 2>&1 &
    SERVICE_PID=$!
    echo $SERVICE_PID > "$PID_FILE"
    echo "✅ 模型推理服务已启动 (PID: $SERVICE_PID)"
    return $SERVICE_PID
}

# 启动服务
start_service
SERVICE_PID=$?

# 等待几秒检查服务是否正常启动
sleep 5

# 检查服务是否还在运行
if ! ps -p "$SERVICE_PID" > /dev/null 2>&1; then
    echo "❌ 服务启动失败，请查看日志: tail -f $LOG_FILE"
    rm -f "$PID_FILE"
    exit 1
fi

echo ""
echo "=========================================="
echo "✅ 服务运行中"
echo "=========================================="
echo "PID: $SERVICE_PID"
echo "PID 文件: $PID_FILE"
echo "日志文件: $LOG_FILE"
echo "服务地址: http://0.0.0.0:$PORT"
echo "健康检查: curl http://localhost:$PORT/health"
echo ""
echo "查看日志: tail -f $LOG_FILE"
echo "停止服务: kill $SERVICE_PID 或 rm -f $PID_FILE"
echo "=========================================="

